declare namespace pm = "http://www.politicalmashup.nl";

let $members := collection('/db/projdb/ge-2009')/root/pm:proceedings/pm:topic/pm:stage-direction/pm:members/pm:person

let $speakers := distinct-values( 
    for $m in $members
        return data($m/@pm:speaker)
)


let $clusters := document('/db/projdb/clusters-ge-2009.xml')/speakers/speaker/subjects/subject
         
let $allTopics := collection('/db/projdb/ge-2009')/root/pm:proceedings/pm:topic

let $outputByClusters := element clusters {
    for $cluster in $clusters
        let $splittedLabels := tokenize( $cluster/label, ",\s" )
        return element cluster {
            element fullLabel {
                data( $cluster/label)
            },
            let $currentDocument := $cluster/documents/document
            let $topics :=  
                for $currentTopic in $allTopics
                    for $currentId in $currentDocument
                    where ( data( $currentId ) = data( $currentTopic/@pm:id ) )
                        return $currentTopic            
            
            for $splittedLabel in $splittedLabels
                return element labels {
                    element label { 
                        element name {
                            data($splittedLabel)
                        },

                        for $topic in $topics
                        let $temp := string-join(data($topic/pm:speech/pm:p),"")
                        where ( contains( lower-case(data($temp)), lower-case(data($splittedLabel)) ) )
                            return element t {
                                element id {
                                    data($topic/@pm:id) 
                                },
                                let $speakerCollection := distinct-values( 
                                    for $speech in $topic/pm:speech
                                    where( contains( lower-case(data(string-join(data($speech/pm:p),""))), lower-case(data($splittedLabel)) ) )
                                        return data($speech/@pm:speaker)
                                )
                                    
                                for $s in $speakerCollection
                                    return element s {
                                        data($s)
                                    }
                            }
                    }
                }
        }
}
        
let $collection := 'xmldb:exist:///db/projdb'
let $file-name := 'clusterdata.xml'

let $store-return-status := xmldb:store($collection, $file-name, $outputByClusters )

return <message>New Document Created {$store-return-status} at {$collection}/{$file-name}</message>
